Merge branch 'main' into chat-cross-client-echo-order
This commit is contained in:
@@ -42,6 +42,10 @@ type chatBroker interface {
|
||||
Reply(ctx context.Context, request protocol.ChatReplyRequest) error
|
||||
}
|
||||
|
||||
type chatShellOutputReader interface {
|
||||
ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error)
|
||||
}
|
||||
|
||||
// chatShellReleaser is implemented by brokers that retain verified shell ids for
|
||||
// attributing exit events. The hub calls it only after the last observer leaves
|
||||
// a room; a later attach obtains a fresh authoritative snapshot.
|
||||
@@ -128,6 +132,12 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatReopen:
|
||||
handleChatReopen(ctx, request, registry, write)
|
||||
return true
|
||||
case protocol.ChatShells:
|
||||
handleChatShells(ctx, request, broker, registry, write)
|
||||
return true
|
||||
case protocol.ChatShellOutput:
|
||||
handleChatShellOutput(ctx, request, broker, registry, write)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func operatorChatSession(ctx context.Context, registry operatorRegistry, id string) error {
|
||||
if registry == nil {
|
||||
return fmt.Errorf("operator session registry is not configured on this server")
|
||||
}
|
||||
_, found, err := registry.OperatorSession(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("operator session is not available")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleChatShells(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
|
||||
query := request.ChatQuery
|
||||
if broker == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if err := operatorChatSession(ctx, registry, query.SessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
shells, err := broker.Shells(ctx, query.SessionID)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatShells, ID: request.ID, ChatShells: shells})
|
||||
}
|
||||
|
||||
func handleChatShellOutput(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
|
||||
query := request.ChatShellOutputQuery
|
||||
if broker == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid bounded shell output query is required"})
|
||||
return
|
||||
}
|
||||
if err := operatorChatSession(ctx, registry, query.SessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
reader, ok := broker.(chatShellOutputReader)
|
||||
if !ok {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "shell output is not configured on this server"})
|
||||
return
|
||||
}
|
||||
output, err := reader.ShellOutput(ctx, *query)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatShellOutput, ID: request.ID, ChatShellOutput: &output})
|
||||
}
|
||||
|
||||
func validShellID(id string) bool {
|
||||
return opencode.ValidShellID(id)
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type shellOutputTestBroker struct {
|
||||
*fakeChat
|
||||
outputCalls int
|
||||
}
|
||||
|
||||
func (b *shellOutputTestBroker) ShellOutput(context.Context, protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
|
||||
b.outputCalls++
|
||||
return protocol.ChatShellOutputPage{Output: "unexpected"}, nil
|
||||
}
|
||||
|
||||
func TestChatShellOutputRejectsBoundsBeforeRegistryOrProvider(t *testing.T) {
|
||||
store := newOperatorStore(t)
|
||||
broker := &shellOutputTestBroker{fakeChat: scriptedChat()}
|
||||
queries := []protocol.ChatShellOutputQuery{
|
||||
{SessionID: "ses_1", ShellID: "sh_1", Limit: 0},
|
||||
{SessionID: "ses_1", ShellID: "sh_1", Limit: -1},
|
||||
{SessionID: "ses_1", ShellID: "sh_1", Cursor: protocol.ChatShellOutputMaxCursor + 1, Limit: 1},
|
||||
{SessionID: "ses_1", ShellID: "sh_1/../x", Limit: 1},
|
||||
{SessionID: "ses_1", ShellID: "sh_1%2f", Limit: 1},
|
||||
{SessionID: "ses_1", ShellID: "sh_1?cursor=0", Limit: 1},
|
||||
{SessionID: "ses_1", ShellID: "sh_1#fragment", Limit: 1},
|
||||
{SessionID: "ses_1", ShellID: "sh_%ZZ", Limit: 1},
|
||||
{SessionID: "ses_1", ShellID: "sh_" + string(make([]byte, 126)), Limit: 1},
|
||||
}
|
||||
for _, query := range queries {
|
||||
var response protocol.Message
|
||||
handleChatShellOutput(context.Background(), protocol.Message{ChatShellOutputQuery: &query}, broker, store, func(m protocol.Message) error {
|
||||
response = m
|
||||
return nil
|
||||
})
|
||||
if response.Type != protocol.Error {
|
||||
t.Fatalf("query %+v response = %+v", query, response)
|
||||
}
|
||||
}
|
||||
if broker.outputCalls != 0 {
|
||||
t.Fatalf("invalid queries reached provider %d times", broker.outputCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatShellOutputRealHandlerWebsocketOwnedAndForeign drives the real
|
||||
// authenticated adapter, HTTP fixture, HandlerWithOptions, and /connect path.
|
||||
// The foreign detail deliberately has a marker that would be returned by its
|
||||
// output route; the session metadata check must reject it first.
|
||||
func TestChatShellOutputRealHandlerWebsocketOwnedAndForeign(t *testing.T) {
|
||||
testChatShellOutputOwnedAndForeign(t, false)
|
||||
}
|
||||
|
||||
func TestChatShellOutputRealHandlerExitedReadback(t *testing.T) {
|
||||
testChatShellOutputOwnedAndForeign(t, true)
|
||||
}
|
||||
|
||||
func testChatShellOutputOwnedAndForeign(t *testing.T, exited bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var providerRequests atomic.Int32
|
||||
fixtureHandler := LargeChatFixtureHandlerWithShell(t.TempDir(), exited)
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
providerRequests.Add(1)
|
||||
fixtureHandler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer fixture.Close()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, LargeChatFixtureSessionID, t.TempDir(), "owned", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: opencode.NewChat(attached.Connection), OperatorRegistry: store}))
|
||||
defer srv.Close()
|
||||
ws := dialShellOutputWebsocket(t, ctx, srv)
|
||||
defer ws.CloseNow()
|
||||
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShells, ID: "owned-shells", ChatQuery: &protocol.ChatQuery{SessionID: LargeChatFixtureSessionID}})
|
||||
owned := readShellOutputMessage(t, ctx, ws)
|
||||
if owned.Type != protocol.ChatShells || (exited && len(owned.ChatShells) != 0) || (!exited && (len(owned.ChatShells) != 1 || owned.ChatShells[0].ID != LargeChatFixtureShellID || owned.ChatShells[0].Status != protocol.ChatShellRunning)) {
|
||||
t.Fatalf("owned shell listing = %+v", owned)
|
||||
}
|
||||
wantStatus := protocol.ChatShellRunning
|
||||
if exited {
|
||||
wantStatus = protocol.ChatShellExited
|
||||
}
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "owned-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: LargeChatFixtureSessionID, ShellID: LargeChatFixtureShellID, Limit: protocol.ChatShellOutputLimit}})
|
||||
page := readShellOutputMessage(t, ctx, ws)
|
||||
if page.Type != protocol.ChatShellOutput || page.ChatShellOutput == nil || page.ChatShellOutput.Output != LargeChatFixtureShellOutput || page.ChatShellOutput.Cursor != int64(len(LargeChatFixtureShellOutput)) || page.ChatShellOutput.Shell.Status != wantStatus {
|
||||
t.Fatalf("owned output page = %+v", page)
|
||||
}
|
||||
if exited {
|
||||
if page.ChatShellOutput.Shell.Exit == nil || *page.ChatShellOutput.Shell.Exit != 0 {
|
||||
t.Fatalf("selected exited shell readback = %+v", page.ChatShellOutput.Shell)
|
||||
}
|
||||
} else if page.ChatShellOutput.Shell.Exit != nil {
|
||||
t.Fatalf("running shell unexpectedly has exit = %+v", page.ChatShellOutput.Shell.Exit)
|
||||
}
|
||||
if page.ChatShellOutput.Cursor != int64(len(page.ChatShellOutput.Output)) || page.ChatShellOutput.Size != page.ChatShellOutput.Cursor {
|
||||
t.Fatalf("non-deterministic output cursor/size = %+v", page.ChatShellOutput)
|
||||
}
|
||||
refusals := []struct {
|
||||
name string
|
||||
request protocol.Message
|
||||
}{
|
||||
{name: "foreign-output", request: protocol.Message{Type: protocol.ChatShellOutput, ID: "foreign-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: LargeChatFixtureSessionID, ShellID: LargeChatFixtureForeignShellID, Limit: protocol.ChatShellOutputLimit}}},
|
||||
{name: "foreign-list", request: protocol.Message{Type: protocol.ChatShells, ID: "foreign-list", ChatQuery: &protocol.ChatQuery{SessionID: LargeChatFixtureForeignSessionID}}},
|
||||
{name: "syntax-invalid-list", request: protocol.Message{Type: protocol.ChatShells, ID: "invalid-list", ChatQuery: &protocol.ChatQuery{SessionID: "ses_bad/invalid"}}},
|
||||
{name: "unknown-output", request: protocol.Message{Type: protocol.ChatShellOutput, ID: "unknown-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: "ses_unregistered_fixture", ShellID: LargeChatFixtureShellID, Limit: protocol.ChatShellOutputLimit}}},
|
||||
}
|
||||
for _, refusal := range refusals {
|
||||
beforeRefusal := providerRequests.Load()
|
||||
writeChat(t, ctx, ws, refusal.request)
|
||||
response := readShellOutputMessage(t, ctx, ws)
|
||||
if response.Type != protocol.Error || strings.Contains(response.Error, LargeChatFixtureForeignShellOutput) {
|
||||
t.Fatalf("%s response leaked or succeeded: %+v", refusal.name, response)
|
||||
}
|
||||
if got := providerRequests.Load(); got != beforeRefusal {
|
||||
t.Fatalf("%s reached provider: requests %d -> %d", refusal.name, beforeRefusal, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatShellOutputRealHandlerUnavailableAndReconnect(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
fixture := httptest.NewServer(LargeChatFixtureHandlerWithShell(t.TempDir(), false))
|
||||
defer fixture.Close()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, LargeChatFixtureSessionID, t.TempDir(), "owned", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: opencode.NewChat(attached.Connection), OperatorRegistry: store}))
|
||||
defer srv.Close()
|
||||
ws := dialShellOutputWebsocket(t, ctx, srv)
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "missing-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: LargeChatFixtureSessionID, ShellID: "sh_missing_fixture", Limit: 64}})
|
||||
missing := readShellOutputMessage(t, ctx, ws)
|
||||
if missing.Type != protocol.ChatShellOutput || missing.ChatShellOutput == nil || !missing.ChatShellOutput.Unavailable {
|
||||
t.Fatalf("404 shell output = %+v", missing)
|
||||
}
|
||||
ws = dialShellOutputWebsocket(t, ctx, srv)
|
||||
defer ws.CloseNow()
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShells, ID: "reconnect", ChatQuery: &protocol.ChatQuery{SessionID: LargeChatFixtureSessionID}})
|
||||
if got := readShellOutputMessage(t, ctx, ws); got.Type != protocol.ChatShells {
|
||||
t.Fatalf("reconnect shell listing = %+v", got)
|
||||
}
|
||||
if _, err := opencode.OpenEndpointAttached(ctx, fixture.URL, "wrong-password", "", ""); err == nil {
|
||||
t.Fatal("wrong provider authentication unexpectedly succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatShellOutputRejectsMalformedAndOversizedProviderPages(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
output string
|
||||
}{
|
||||
{name: "malformed", output: `{"data":{"output":"x"}}`},
|
||||
{name: "oversized", output: fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, strings.Repeat("x", protocol.ChatShellOutputLimit+1), protocol.ChatShellOutputLimit+1, protocol.ChatShellOutputLimit+1)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/info":
|
||||
_, _ = w.Write([]byte(`{"version":"fixture","urls":[]}`))
|
||||
case "/api/event":
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
case "/api/shell/sh_malformed_fixture":
|
||||
_, _ = w.Write([]byte(`{"data":{"id":"sh_malformed_fixture","status":"running","metadata":{"sessionID":"ses_malformed_fixture"}}}`))
|
||||
case "/api/shell/sh_malformed_fixture/output":
|
||||
_, _ = w.Write([]byte(tc.output))
|
||||
default:
|
||||
if r.URL.Path == "/api/shell" {
|
||||
_, _ = w.Write([]byte(`{"data":[]}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer fixture.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = opencode.NewChat(attached.Connection).ShellOutput(ctx, protocol.ChatShellOutputQuery{SessionID: "ses_malformed_fixture", ShellID: "sh_malformed_fixture", Limit: protocol.ChatShellOutputLimit})
|
||||
if err == nil {
|
||||
t.Fatalf("%s provider page was accepted", tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatShellOutputRealHandlerCancellationStopsProvider(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
canceled := make(chan struct{})
|
||||
fixtureHandler := LargeChatFixtureHandlerWithShell(t.TempDir(), false)
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/shell/sh_cancel_fixture" {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
close(canceled)
|
||||
return
|
||||
}
|
||||
fixtureHandler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer fixture.Close()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, "ses_cancel_fixture", t.TempDir(), "cancel", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
serverCtx, serverCancel := context.WithCancel(ctx)
|
||||
defer serverCancel()
|
||||
srv := httptest.NewServer(HandlerWithOptions(serverCtx, Options{Chat: opencode.NewChat(attached.Connection), OperatorRegistry: store}))
|
||||
defer srv.Close()
|
||||
ws := dialShellOutputWebsocket(t, ctx, srv)
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "cancel-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: "ses_cancel_fixture", ShellID: "sh_cancel_fixture", Limit: 64}})
|
||||
select {
|
||||
case <-started:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("provider detail request did not start")
|
||||
}
|
||||
serverCancel()
|
||||
select {
|
||||
case <-canceled:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("canceling handler did not cancel provider request")
|
||||
}
|
||||
}
|
||||
|
||||
func dialShellOutputWebsocket(t *testing.T, ctx context.Context, srv *httptest.Server) *websocket.Conn {
|
||||
t.Helper()
|
||||
ws, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
func readShellOutputMessage(t *testing.T, ctx context.Context, ws *websocket.Conn) protocol.Message {
|
||||
t.Helper()
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, ws, &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return message
|
||||
}
|
||||
@@ -341,20 +341,23 @@ func TestRetryConflictsOnlyWithSameWorkspaceActiveRun(t *testing.T) {
|
||||
if err != nil || failed.Status != "failed" {
|
||||
t.Fatalf("original run did not fail as intended: %+v %v", failed, err)
|
||||
}
|
||||
resolvedB, err := filepath.EvalSymlinks(b)
|
||||
entered := make(chan struct{}, 4)
|
||||
resolvedA, err := filepath.EvalSymlinks(a)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered := make(chan struct{}, 4)
|
||||
release := make(chan struct{})
|
||||
releaseA := make(chan struct{})
|
||||
releaseB := make(chan struct{})
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
entered <- struct{}{}
|
||||
if input["pwd"] == resolvedB {
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
release := releaseB
|
||||
if input["pwd"] == resolvedA {
|
||||
release = releaseA
|
||||
}
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
@@ -366,6 +369,7 @@ func TestRetryConflictsOnlyWithSameWorkspaceActiveRun(t *testing.T) {
|
||||
if _, err := r.retry(protocol.Message{RunID: original.ID, RequestKey: "retry-a"}); err == nil || !strings.Contains(err.Error(), fmt.Sprintf("run %d is already active", activeA.ID)) || !strings.Contains(err.Error(), "different workspace") {
|
||||
t.Fatalf("retry did not conflict with same-workspace active run: %v", err)
|
||||
}
|
||||
close(releaseA)
|
||||
// A different active workspace must not block the retry of the original.
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "active-b", Workspace: b, Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -378,7 +382,7 @@ func TestRetryConflictsOnlyWithSameWorkspaceActiveRun(t *testing.T) {
|
||||
if retried.Workspace != failed.Workspace {
|
||||
t.Fatalf("retry did not reuse the original workspace: %q != %q", retried.Workspace, failed.Workspace)
|
||||
}
|
||||
close(release)
|
||||
close(releaseB)
|
||||
r.wg.Wait()
|
||||
}
|
||||
|
||||
|
||||
@@ -270,7 +270,7 @@ func TestHumanStageCancelRetryAndRebuild(t *testing.T) {
|
||||
t.Fatalf("post-decision failure did not fail the run: %+v", failed.RunSummary)
|
||||
}
|
||||
r3.execute = successExecute
|
||||
retried, err := r3.retry(protocol.Message{RunID: failing.ID, RequestKey: "retry-human"})
|
||||
retried, err := r3.retry(protocol.Message{RunID: failing.ID, RequestKey: "retry-human", RetryMode: "restart"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,11 @@ const LargeChatFixtureSessionID = "ses_large_chat_fixture"
|
||||
// LargeChatFixturePassword authenticates the disposable fixture endpoint. It is
|
||||
// fixed fixture data, not an operator credential.
|
||||
const LargeChatFixturePassword = "large-chat-fixture"
|
||||
const LargeChatFixtureShellID = "sh_large_chat_fixture"
|
||||
const LargeChatFixtureShellOutput = "fixture shell output marker\n"
|
||||
const LargeChatFixtureForeignSessionID = "ses_foreign_fixture"
|
||||
const LargeChatFixtureForeignShellID = "sh_foreign_fixture"
|
||||
const LargeChatFixtureForeignShellOutput = "FOREIGN SHELL MARKER MUST NOT LEAK\n"
|
||||
|
||||
const (
|
||||
LargeChatFixtureNewestAnswer = "Controlled newest answer: large history fixture"
|
||||
@@ -24,6 +29,13 @@ const (
|
||||
// It deliberately serves fixed, paged data: no model is invoked and no production
|
||||
// history is read or written.
|
||||
func LargeChatFixtureHandler(workspace string) http.Handler {
|
||||
return LargeChatFixtureHandlerWithShell(workspace, false)
|
||||
}
|
||||
|
||||
// LargeChatFixtureHandlerWithShell is the foreground fixture surface used by
|
||||
// the readback check. exited selects the provider's observed terminal state;
|
||||
// the output remains fixed and bounded in either state.
|
||||
func LargeChatFixtureHandlerWithShell(workspace string, exited bool) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/info", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
@@ -63,6 +75,46 @@ func LargeChatFixtureHandler(workspace string) http.Handler {
|
||||
}
|
||||
writeLargeChatFixturePage(w, page)
|
||||
})
|
||||
status := "running"
|
||||
if exited {
|
||||
status = "exited"
|
||||
}
|
||||
mux.HandleFunc("GET /api/shell", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":[{"id":%q,"status":%q,"command":"printf fixture","metadata":{"sessionID":%q}},{"id":%q,"status":"running","command":"printf foreign","metadata":{"sessionID":%q}}]}`, LargeChatFixtureShellID, status, LargeChatFixtureSessionID, LargeChatFixtureForeignShellID, LargeChatFixtureForeignSessionID))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureShellID, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
exit := "null"
|
||||
if exited {
|
||||
exit = "0"
|
||||
}
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"id":%q,"status":%q,"command":"printf fixture","exit":%s,"metadata":{"sessionID":%q}}}`, LargeChatFixtureShellID, status, exit, LargeChatFixtureSessionID))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureForeignShellID, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"id":%q,"status":"running","command":"printf foreign","metadata":{"sessionID":%q}}}`, LargeChatFixtureForeignShellID, LargeChatFixtureForeignSessionID))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureShellID+"/output", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
cursor := int64(len(LargeChatFixtureShellOutput))
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, LargeChatFixtureShellOutput, cursor, cursor))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureForeignShellID+"/output", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
cursor := int64(len(LargeChatFixtureForeignShellOutput))
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, LargeChatFixtureForeignShellOutput, cursor, cursor))
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -15,11 +16,30 @@ import (
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/cli"
|
||||
"git.a-wan.net/alan/pipelines/internal/client"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
)
|
||||
|
||||
type fixedRemoteListener struct{ net.Listener }
|
||||
|
||||
func (l fixedRemoteListener) Accept() (net.Conn, error) {
|
||||
conn, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fixedRemoteConn{Conn: conn}, nil
|
||||
}
|
||||
|
||||
type fixedRemoteConn struct{ net.Conn }
|
||||
|
||||
func (fixedRemoteConn) RemoteAddr() net.Addr {
|
||||
return &net.TCPAddr{IP: net.ParseIP("203.0.113.9"), Port: 443}
|
||||
}
|
||||
|
||||
// This is a real CLI/WebSocket/scratch-SQLite exercise with an explicitly FAKE
|
||||
// executor. It never calls inference, a phone, or a deployed server.
|
||||
func TestResourceScratchCLIWaitingThenProgress(t *testing.T) {
|
||||
@@ -110,6 +130,241 @@ func TestResourceScratchCLIWaitingThenProgress(t *testing.T) {
|
||||
t.Log("Observed queued resource wait followed by automatic progress; FAKE executor only, no phone/inference/deployment.")
|
||||
}
|
||||
|
||||
func TestResourceOperatorTransportCLIRecoveryBoundary(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "operator.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
source := pipeline.Template([]string{"work"}, true) + "```resources\n{\"exclusive\":\"scratch-resource\"}\n```\n"
|
||||
if _, err := store.Submit(ctx, "operator-resource", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, _, err := store.CreateRun(ctx, detail, "operator-recovery", t.TempDir(), false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
visit := pipeline.ResourceVisit{Resource: "scratch-resource", RunID: runID, Stage: "work", Sequence: 1}
|
||||
if _, ch, _, err := store.RequestResource(ctx, visit); err != nil || ch != nil {
|
||||
t.Fatalf("acquire resource: channel=%v err=%v", ch, err)
|
||||
}
|
||||
if err := store.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := Handler(ctx, store)
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
normal, err := client.Open(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := normal.Call(ctx, protocol.Message{Type: protocol.InspectResource, Resource: visit.Resource}); err == nil || !strings.Contains(err.Error(), "operator transport") {
|
||||
t.Fatalf("ordinary connect accepted recovery: %v", err)
|
||||
}
|
||||
normal.Close()
|
||||
endpoint := "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect"
|
||||
runCLI := func(args ...string) string {
|
||||
var out bytes.Buffer
|
||||
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
|
||||
if err := app.Run(ctx, append([]string{"--url", endpoint}, args...)); err != nil {
|
||||
t.Fatalf("CLI %v: %v\n%s", args, err, out.String())
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
inspection := runCLI("resource-inspect", visit.Resource, "--json")
|
||||
if strings.Contains(inspection, "token") || strings.Contains(inspection, "credential") {
|
||||
t.Fatalf("inspection leaked capability: %s", inspection)
|
||||
}
|
||||
runCLI("resource-reconcile", visit.Resource, fmt.Sprint(runID), visit.Stage, fmt.Sprint(visit.Sequence), "--evidence", "verified no mutating action", "--yes", "--json")
|
||||
inspection = runCLI("resource-inspect", visit.Resource, "--json")
|
||||
var recovered protocol.ResourceInspection
|
||||
if err := json.Unmarshal([]byte(inspection), &recovered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recovered.Owner != nil || len(recovered.Audits) != 1 || recovered.Audits[0].RunID != runID || recovered.Audits[0].Result != "reconciled" {
|
||||
t.Fatalf("CLI recovery state was not persisted: %s", inspection)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceOperatorCLIRejectsStaleAndNonQuarantinedRecovery(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "operator-rejections.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "operator-rejections", pipeline.Template([]string{"work"}, true)+"```resources\n{\"exclusive\":\"scratch-resource\"}\n```\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, _, err := store.CreateRun(ctx, detail, "operator-rejections", t.TempDir(), false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
visit := pipeline.ResourceVisit{Resource: "scratch-resource", RunID: runID, Stage: "work", Sequence: 1}
|
||||
lease, ch, _, err := store.RequestResource(ctx, visit)
|
||||
if err != nil || ch != nil {
|
||||
t.Fatalf("acquire resource: channel=%v err=%v", ch, err)
|
||||
}
|
||||
if err := store.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := Handler(ctx, store)
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
endpoint := "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect"
|
||||
runCLI := func(args ...string) error {
|
||||
var out bytes.Buffer
|
||||
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
|
||||
err := app.Run(ctx, append([]string{"--url", endpoint}, args...))
|
||||
if strings.Contains(out.String(), "token") || strings.Contains(out.String(), "credential") {
|
||||
t.Fatalf("private capability appeared in CLI output: %s", out.String())
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := runCLI("resource-reconcile", visit.Resource, fmt.Sprint(runID+1), visit.Stage, fmt.Sprint(visit.Sequence), "--evidence", "verified", "--yes", "--json"); err == nil {
|
||||
t.Fatal("accepted wrong owner")
|
||||
}
|
||||
if err := runCLI("resource-reconcile", visit.Resource, fmt.Sprint(runID), "stale-stage", fmt.Sprint(visit.Sequence), "--evidence", "verified", "--yes", "--json"); err == nil {
|
||||
t.Fatal("accepted stale stage")
|
||||
}
|
||||
if err := runCLI("resource-reconcile", visit.Resource, fmt.Sprint(runID), visit.Stage, "2", "--evidence", "verified", "--yes", "--json"); err == nil {
|
||||
t.Fatal("accepted stale sequence")
|
||||
}
|
||||
if err := store.SetResourceCleanup(ctx, lease, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runCLI("resource-reconcile", visit.Resource, fmt.Sprint(runID), visit.Stage, fmt.Sprint(visit.Sequence), "--evidence", "verified", "--yes", "--json"); err == nil {
|
||||
t.Fatal("accepted non-quarantined owner")
|
||||
}
|
||||
inspection, err := store.InspectResource(ctx, visit.Resource)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if inspection.Owner == nil || !inspection.Owner.CleanupConfirmed || len(inspection.Audits) != 0 {
|
||||
t.Fatalf("rejected recovery changed state: owner=%#v audits=%d", inspection.Owner, len(inspection.Audits))
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceOperatorTransportDoesNotTrustRemoteOrForwardedHeaders(t *testing.T) {
|
||||
for _, remote := range []string{"203.0.113.9:443", "198.51.100.7:8080", "not-an-address"} {
|
||||
if isLoopbackPeer(remote) {
|
||||
t.Fatalf("accepted non-loopback peer %q", remote)
|
||||
}
|
||||
}
|
||||
for _, remote := range []string{"127.0.0.1:443", "[::1]:443"} {
|
||||
if !isLoopbackPeer(remote) {
|
||||
t.Fatalf("rejected loopback peer %q", remote)
|
||||
}
|
||||
}
|
||||
// X-Forwarded-For is deliberately not consulted: a proxy-supplied header
|
||||
// cannot turn a remote WebSocket peer into the local operator transport.
|
||||
}
|
||||
|
||||
func TestResourceOperatorTransportRejectsForgedForwardedPeer(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "operator-transport.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "operator-transport", pipeline.Template([]string{"work"}, true)+"```resources\n{\"exclusive\":\"scratch-resource\"}\n```\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, _, err := store.CreateRun(ctx, detail, "operator-transport", t.TempDir(), false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
visit := pipeline.ResourceVisit{Resource: "scratch-resource", RunID: runID, Stage: "work", Sequence: 1}
|
||||
if _, ch, _, err := store.RequestResource(ctx, visit); err != nil || ch != nil {
|
||||
t.Fatalf("acquire resource: channel=%v err=%v", ch, err)
|
||||
}
|
||||
if err := store.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := store.InspectResource(ctx, visit.Resource)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
server := httptest.NewUnstartedServer(Handler(ctx, store))
|
||||
server.Listener = fixedRemoteListener{Listener: server.Listener}
|
||||
server.Start()
|
||||
defer server.Close()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http")+"/operator-connect", &websocket.DialOptions{HTTPHeader: map[string][]string{"X-Forwarded-For": {"127.0.0.1"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
var welcome protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &welcome); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.InspectResource, Resource: visit.Resource, ID: "forged"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var refused protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &refused); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refused.Type != protocol.Error || !strings.Contains(refused.Error, "operator transport") {
|
||||
t.Fatalf("forged peer was accepted: %#v", refused)
|
||||
}
|
||||
after, err := store.InspectResource(ctx, visit.Resource)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(before, after) {
|
||||
t.Fatalf("forged request mutated recovery state: before=%#v after=%#v", before, after)
|
||||
}
|
||||
|
||||
trusted := httptest.NewServer(Handler(ctx, store))
|
||||
defer trusted.Close()
|
||||
normal, err := client.Open(ctx, "ws"+strings.TrimPrefix(trusted.URL, "http")+"/connect")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := normal.Call(ctx, protocol.Message{Type: protocol.InspectResource, Resource: visit.Resource}); err == nil || !strings.Contains(err.Error(), "operator transport") {
|
||||
t.Fatalf("ordinary connect accepted recovery: %v", err)
|
||||
}
|
||||
normal.Close()
|
||||
operator, err := client.Open(ctx, "ws"+strings.TrimPrefix(trusted.URL, "http")+"/operator-connect")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer operator.Close()
|
||||
if _, err := operator.Call(ctx, protocol.Message{Type: protocol.InspectResource, Resource: visit.Resource}); err != nil {
|
||||
t.Fatalf("trusted operator transport refused inspection: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceAndroidDraftPublishedV3Provenance(t *testing.T) {
|
||||
baseline, err := os.ReadFile("testdata/android-v3-published.md")
|
||||
if err != nil {
|
||||
|
||||
@@ -43,14 +43,14 @@ func TestRetryWaitsForExecutionCleanupEvenAfterTerminalStatus(t *testing.T) {
|
||||
if err != nil || !runs[0].Executing {
|
||||
t.Fatal("list advertised stopped run during cleanup", runs, err)
|
||||
}
|
||||
if _, err := r.retry(protocol.Message{RunID: id, RequestKey: "retry"}); err == nil || !strings.Contains(err.Error(), "still executing") {
|
||||
if _, err := r.retry(protocol.Message{RunID: id, RequestKey: "retry", RetryMode: "restart"}); err == nil || !strings.Contains(err.Error(), "still executing") {
|
||||
t.Fatal("retry accepted during execution cleanup", err)
|
||||
}
|
||||
delete(r.active, id)
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
}
|
||||
if _, err := r.retry(protocol.Message{RunID: id, RequestKey: "retry"}); err != nil {
|
||||
if _, err := r.retry(protocol.Message{RunID: id, RequestKey: "retry", RetryMode: "restart"}); err != nil {
|
||||
t.Fatal("retry rejected after cleanup", err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
|
||||
@@ -183,7 +183,7 @@ func TestRetryReplaysInitialInputAndPinnedVersionThroughCLI(t *testing.T) {
|
||||
if err != nil || len(beforeRetry) != 1 {
|
||||
t.Fatal("unconfirmed retry created a run", err)
|
||||
}
|
||||
result, err := runCLI("retry", fmt.Sprint(original.ID), "--yes", "--json", "--wait", "--timeout", "5s", "--request-key", "retry-key")
|
||||
result, err := runCLI("retry", fmt.Sprint(original.ID), "--yes", "--json", "--wait", "--timeout", "5s", "--request-key", "retry-key", "--mode", "restart")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -236,7 +236,7 @@ func TestRetryRejectsUnavailableOriginalDirectoryAndNonfailedRuns(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
_, err = r.retry(protocol.Message{RunID: id, RequestKey: "retry-" + status})
|
||||
_, err = r.retry(protocol.Message{RunID: id, RequestKey: "retry-" + status, RetryMode: "restart"})
|
||||
if err == nil {
|
||||
t.Fatal("invalid retry accepted", status)
|
||||
}
|
||||
@@ -249,6 +249,95 @@ func TestRetryRejectsUnavailableOriginalDirectoryAndNonfailedRuns(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
dir := t.TempDir()
|
||||
store, err := pipeline.Open(filepath.Join(dir, "resume.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := "# stage a\n\n```output\nA\n```\n\n```prompt\nA\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=test\nmodel=test\n```\n\n# stage b\n\n```output\nB\n```\n\n```prompt\nB\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=test\nmodel=test\n```\n\n# stage c\n\n```output\nC\n```\n\n```prompt\nC\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=test\nmodel=test\n```\n"
|
||||
if _, err := store.Submit(ctx, "resume", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
workspace := t.TempDir()
|
||||
var aCalls, bCalls, cCalls int
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
switch def.Key {
|
||||
case "a":
|
||||
aCalls++
|
||||
if input["prompt"] != "task" {
|
||||
t.Errorf("entry received altered input: %#v", input)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-a"}}, nil
|
||||
case "b":
|
||||
bCalls++
|
||||
if input["handoff"] != "from-a" {
|
||||
t.Errorf("resume lost exact prefix handoff: %#v", input)
|
||||
}
|
||||
if bCalls == 1 {
|
||||
return stage.Result{}, fmt.Errorf("deliberate failure")
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil
|
||||
case "c":
|
||||
cCalls++
|
||||
if input["handoff"] != "from-b" {
|
||||
t.Errorf("C received wrong handoff: %#v", input)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected stage %q", def.Key)
|
||||
return stage.Result{}, nil
|
||||
}
|
||||
}
|
||||
original, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "original", Workspace: workspace, Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
original, err = store.GetRun(ctx, original.ID)
|
||||
if err != nil || original.Status != "failed" || len(original.Steps) != 2 {
|
||||
t.Fatalf("initial run did not stop at B: %+v %v", original, err)
|
||||
}
|
||||
retried, err := r.retry(protocol.Message{RunID: original.ID, RequestKey: "resume-key"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
retried, err = store.GetRun(ctx, retried.ID)
|
||||
if err != nil || retried.Status != "succeeded" || retried.RetryMode != "resume" || retried.RetrySource != original.ID {
|
||||
t.Fatalf("resume did not complete with provenance: %+v %v", retried, err)
|
||||
}
|
||||
if aCalls != 1 || bCalls != 2 || cCalls != 1 {
|
||||
t.Fatalf("retry duplicated prefix or suffix: A=%d B=%d C=%d", aCalls, bCalls, cCalls)
|
||||
}
|
||||
if len(retried.Steps) != 2 || retried.Steps[0].Stage != "b" || retried.Steps[1].Stage != "c" {
|
||||
t.Fatalf("retry persisted the wrong steps: %+v", retried.Steps)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = pipeline.Open(filepath.Join(dir, "resume.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
r2, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replayed, err := r2.retry(protocol.Message{RunID: original.ID, RequestKey: "resume-key"})
|
||||
if err != nil || replayed.ID != retried.ID {
|
||||
t.Fatalf("persisted request-key replay lost its run: %+v %v", replayed, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadOnlyStageRetriesPostAdmissionTransportButMutatingStageDoesNot proves,
|
||||
// through the real runner and CLI fixture, that a read-only stage retries a
|
||||
// post-admission transport (final-readback) failure with a fresh session while
|
||||
|
||||
+145
-1
@@ -285,6 +285,15 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
|
||||
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
|
||||
}
|
||||
if created {
|
||||
if request.RetrySource > 0 && request.RetryMode != "restart" {
|
||||
checkpoint, checkpointErr := r.retrySourceCheckpoint(request.RetrySource, d)
|
||||
if checkpointErr != nil {
|
||||
return nil, checkpointErr
|
||||
}
|
||||
if err := r.store.SaveRetryCheckpoint(r.ctx, id, request.RetrySource, "resume", checkpoint.failed.Sequence, checkpoint.detail, checkpoint.handoff); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Emit the created delta before launching: the queued frame reaches
|
||||
// subscribers before the running/step-started transition, so a client
|
||||
// sees the run appear and then advance.
|
||||
@@ -404,6 +413,65 @@ func (r *runner) listRuns() ([]protocol.RunSummary, error) {
|
||||
return items, err
|
||||
}
|
||||
|
||||
type retryCheckpoint struct {
|
||||
detail *protocol.RunDetail
|
||||
failed protocol.RunStep
|
||||
handoff map[string]any
|
||||
}
|
||||
|
||||
func (r *runner) retrySourceCheckpoint(sourceID int64, pinned *protocol.PipelineDetail) (retryCheckpoint, error) {
|
||||
source, err := r.store.GetRun(r.ctx, sourceID)
|
||||
if err != nil {
|
||||
return retryCheckpoint{}, err
|
||||
}
|
||||
if source.Status != "failed" || source.FinishedAt == "" {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed run", sourceID)
|
||||
}
|
||||
if source.PipelineID != pinned.ID || source.Version != pinned.Version || source.ContentHash != pinned.ContentHash {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d is pinned to a different pipeline version", sourceID)
|
||||
}
|
||||
if len(source.Steps) == 0 {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID)
|
||||
}
|
||||
failed := source.Steps[len(source.Steps)-1]
|
||||
if (failed.Status != "completed" && failed.Status != "failed") || failed.Target != protocol.FailureEnd {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe failed-stage checkpoint", sourceID)
|
||||
}
|
||||
var handoff map[string]any
|
||||
if failed.Input == nil {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d is missing failed-stage handoff context", sourceID)
|
||||
}
|
||||
handoff = map[string]any{"input": failed.Input, "sequence": failed.Sequence, "stage": failed.Stage}
|
||||
prefix := map[string]any{}
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence >= failed.Sequence || step.Status != "completed" {
|
||||
continue
|
||||
}
|
||||
prefix[step.Stage] = step.Output
|
||||
}
|
||||
handoff["prefix"] = prefix
|
||||
for _, declared := range pinned.Graph.Stages {
|
||||
if declared.Key != failed.Stage {
|
||||
continue
|
||||
}
|
||||
typ := stage.EffectiveType(declared.Type)
|
||||
if typ == stage.HumanType || typ == stage.NtfyType {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d cannot replay completed external stage %s", sourceID, failed.Stage)
|
||||
}
|
||||
if typ == stage.ModelType {
|
||||
tools, explicit, toolErr := stage.ToolNames(pipeline.StageDefinition(declared))
|
||||
if toolErr != nil {
|
||||
return retryCheckpoint{}, toolErr
|
||||
}
|
||||
if explicit && len(tools) > 0 {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d cannot safely replay admitted native stage %s", sourceID, failed.Stage)
|
||||
}
|
||||
}
|
||||
return retryCheckpoint{detail: source, failed: failed, handoff: handoff}, nil
|
||||
}
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d failed stage is not in the pinned graph", sourceID)
|
||||
}
|
||||
|
||||
func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if request.RunID <= 0 {
|
||||
return nil, fmt.Errorf("retry requires a positive run ID")
|
||||
@@ -418,7 +486,26 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if original.Status != "failed" || original.FinishedAt == "" {
|
||||
return nil, fmt.Errorf("only failed runs can be retried (run %d is %s)", original.ID, original.Status)
|
||||
}
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: original.Version, RequestKey: request.RequestKey, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels}, original.ID)
|
||||
if request.RequestKey == "" {
|
||||
return nil, fmt.Errorf("retry requires an idempotency request key")
|
||||
}
|
||||
mode := request.RetryMode
|
||||
if mode == "" {
|
||||
mode = "resume"
|
||||
}
|
||||
if mode != "resume" && mode != "restart" {
|
||||
return nil, fmt.Errorf("retry mode must be resume or restart")
|
||||
}
|
||||
d, err := r.store.Get(r.ctx, original.PipelineID, original.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mode == "resume" {
|
||||
if _, err := r.retrySourceCheckpoint(original.ID, d); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: original.Version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels}, original.ID)
|
||||
}
|
||||
|
||||
func (r *runner) cancel(id int64) error {
|
||||
@@ -520,6 +607,35 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
}
|
||||
|
||||
func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, workspace string, request protocol.Message) {
|
||||
if request.RetrySource > 0 && request.RetryMode != "restart" {
|
||||
source, err := r.store.GetRun(ctx, request.RetrySource)
|
||||
if err != nil {
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
checkpoint, err := r.retrySourceCheckpoint(request.RetrySource, d)
|
||||
if err != nil {
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
storedSource, storedMode, storedSequence, storedHandoff, checkpointErr := r.store.RetryCheckpoint(ctx, id)
|
||||
if checkpointErr != nil || storedSource != request.RetrySource || storedMode != "resume" || storedSequence != checkpoint.failed.Sequence || storedHandoff == nil {
|
||||
if checkpointErr == nil {
|
||||
checkpointErr = fmt.Errorf("retry checkpoint is incomplete")
|
||||
}
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", checkpointErr.Error(), 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
if input, ok := storedHandoff["input"].(map[string]any); ok {
|
||||
checkpoint.failed.Input = input
|
||||
} else {
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", "retry checkpoint is missing handoff context", 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
state := rebuildRetryState(source, checkpoint.failed)
|
||||
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
|
||||
return
|
||||
}
|
||||
original, copyErr := copyValues(stage.Values(request.Input))
|
||||
if copyErr != nil {
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", copyErr.Error(), 0, 0, "", stage.Values(request.Input))
|
||||
@@ -629,6 +745,34 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS
|
||||
return state
|
||||
}
|
||||
|
||||
// rebuildRetryState restores only the completed prefix. The failed visit is
|
||||
// deliberately not counted and its step/evidence is not copied into the new
|
||||
// attempt, so retries cannot duplicate execution or usage aggregates.
|
||||
func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep) *runState {
|
||||
state := newRunState(failed.Stage, stage.Values(failed.Input))
|
||||
state.nextSequence = failed.Sequence
|
||||
if original, err := copyValues(stage.Values(detail.Input)); err == nil {
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
}
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence >= failed.Sequence {
|
||||
break
|
||||
}
|
||||
state.visits[step.Stage]++
|
||||
if step.Status == "completed" {
|
||||
if values, err := copyValues(stage.Values(step.Output)); err == nil {
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
}
|
||||
state.completed++
|
||||
}
|
||||
state.recordChanges(step.FileChanges, step.Artifacts)
|
||||
if step.Status == "completed" {
|
||||
state.artifactDirs = append(state.artifactDirs, filepath.Join("", strconv.Itoa(step.Sequence)))
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// artifactAccess derives exact visit directories; it never consumes a path from
|
||||
// a definition or model result. An unreadable or symlinked root fails closed.
|
||||
func (r *runner) artifactAccess(runID int64, sequence int, prior []string, current string) stage.ArtifactAccess {
|
||||
|
||||
@@ -2,7 +2,9 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -119,7 +121,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"healthy":true}`))
|
||||
})
|
||||
mux.HandleFunc("GET /connect", func(w http.ResponseWriter, r *http.Request) {
|
||||
connect := func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -171,7 +173,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
}
|
||||
for {
|
||||
var request protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &request); err != nil {
|
||||
if err := wsjson.Read(connCtx, conn, &request); err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version)
|
||||
@@ -268,6 +270,32 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
response.Error = err.Error()
|
||||
}
|
||||
}
|
||||
} else if (request.Type == protocol.InspectResource || request.Type == protocol.ReconcileResource) && len(stores) > 0 {
|
||||
var err error
|
||||
response.Type = protocol.ResourceInspectionResult
|
||||
// Recovery has a separate transport path. A stage/model client may
|
||||
// also be local, so loopback alone is not an authority boundary.
|
||||
// The CLI uses /operator-connect; the ordinary /connect path is
|
||||
// deliberately refused even from loopback.
|
||||
if r.URL.Path != "/operator-connect" || !isLoopbackPeer(r.RemoteAddr) {
|
||||
response.Type = protocol.Error
|
||||
response.Error = "resource recovery requires the local operator transport"
|
||||
} else if request.Type == protocol.InspectResource {
|
||||
var inspection protocol.ResourceInspection
|
||||
inspection, err = stores[0].InspectResource(ctx, request.Resource)
|
||||
response.ResourceInspection = &inspection
|
||||
} else {
|
||||
response.Type = protocol.ResourceReconciled
|
||||
if request.ResourceRecovery == nil {
|
||||
err = fmt.Errorf("resource recovery evidence is required")
|
||||
} else {
|
||||
err = stores[0].ReconcileResource(ctx, *request.ResourceRecovery)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
response.Type = protocol.Error
|
||||
response.Error = err.Error()
|
||||
}
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence) {
|
||||
var err error
|
||||
switch request.Type {
|
||||
@@ -323,10 +351,21 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
}
|
||||
log.Printf("response sent: client=%s type=%q id=%q time=%q error=%q version=%d", r.RemoteAddr, response.Type, response.ID, response.Time, response.Error, selectedVersion)
|
||||
}
|
||||
})
|
||||
}
|
||||
mux.HandleFunc("GET /connect", connect)
|
||||
mux.HandleFunc("GET /operator-connect", connect)
|
||||
return &runHandler{Handler: mux, runner: runs}
|
||||
}
|
||||
|
||||
func isLoopbackPeer(remoteAddr string) bool {
|
||||
host, _, err := net.SplitHostPort(remoteAddr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
type runHandler struct {
|
||||
http.Handler
|
||||
runner *runner
|
||||
|
||||
Reference in New Issue
Block a user