package llm import ( "context" "encoding/json" "errors" "io" "net/http" "os" "path/filepath" "slices" "strings" "testing" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" ck "go.maximumdirect.net/configkit" pk "go.maximumdirect.net/promptkit" ) func boolValue(v bool) *bool { return &v } func positiveSmokeReport() *pk.SmokeTestReport { return &pk.SmokeTestReport{Kind: pk.SmokeTestStructuredOutput, Supported: true, Applicable: boolValue(true), Completed: true, Facts: pk.SmokeTestFacts{GenerationCompleted: boolValue(true), ValidJSON: boolValue(true), SchemaMatched: boolValue(true)}} } func TestStructuredOutputClassification(t *testing.T) { cases := []struct { name string change func(*pk.SmokeTestReport) err error want VerificationStatus }{ {"success without HTTP facts", func(*pk.SmokeTestReport) {}, nil, VerificationSuccess}, {"negative", func(r *pk.SmokeTestReport) { r.Facts.SchemaMatched = boolValue(false) }, nil, VerificationNegative}, {"unsupported", func(r *pk.SmokeTestReport) { r.Supported = false }, nil, VerificationUnsupported}, {"inapplicable", func(r *pk.SmokeTestReport) { r.Applicable = boolValue(false) }, nil, VerificationUnsupported}, {"unknown applicability", func(r *pk.SmokeTestReport) { r.Applicable = nil }, nil, VerificationInconclusive}, {"unknown fact", func(r *pk.SmokeTestReport) { r.Facts.ValidJSON = nil }, nil, VerificationInconclusive}, {"incomplete", func(r *pk.SmokeTestReport) { r.Completed = false }, nil, VerificationInconclusive}, {"wrong kind", func(r *pk.SmokeTestReport) { r.Kind = pk.SmokeTestTextInference }, nil, VerificationInconclusive}, {"native failure", func(r *pk.SmokeTestReport) { r.Failure = pk.ExecutionFailureKind("transport") }, nil, VerificationNegative}, {"error", func(*pk.SmokeTestReport) {}, errors.New("failed"), VerificationNegative}, {"cancellation", func(*pk.SmokeTestReport) {}, context.Canceled, VerificationInconclusive}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { r := positiveSmokeReport() tc.change(r) if got := classifyStructuredOutput(r, tc.err); got != tc.want { t.Fatalf("got %s want %s", got, tc.want) } }) } if got := classifyStructuredOutput(nil, nil); got != VerificationInconclusive { t.Fatalf("nil report: %s", got) } } type smokeFunc func(context.Context, pk.SmokeTestRequest) (*pk.SmokeTestReport, error) func (f smokeFunc) SmokeTest(ctx context.Context, request pk.SmokeTestRequest) (*pk.SmokeTestReport, error) { return f(ctx, request) } func TestVerifyStructuredOutputContinuesAndStopsOnCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() failure := errors.New("failure") var calls []string engine := smokeFunc(func(_ context.Context, request pk.SmokeTestRequest) (*pk.SmokeTestReport, error) { if request.Kind != pk.SmokeTestStructuredOutput || request.Execution != nil || request.TransientRetries != nil || request.PromptID != "" || request.APIKey != "" || request.BackendID != "" { t.Fatalf("unexpected request: %+v", request) } calls = append(calls, request.ProfileID) switch request.ProfileID { case "first": return nil, failure case "second": cancel() return positiveSmokeReport(), context.Canceled default: return positiveSmokeReport(), nil } }) results, err := VerifyStructuredOutput(ctx, engine, []string{"first", "second", "third"}, nil) if !slices.Equal(calls, []string{"first", "second"}) || len(results) != 2 || results[1].Report == nil || !errors.Is(err, failure) || !errors.Is(err, context.Canceled) { t.Fatalf("calls=%v results=%+v error=%v", calls, results, err) } } func TestVerifyStructuredOutputUsesNativeEngine(t *testing.T) { dir := t.TempDir() for name, body := range map[string]string{"config.yml": "version: 3\n", "prompts.yml": "profiles:\n - id: fixture\n endpoint: https://example.invalid/v1\n model: fixture-model\n"} { if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil { t.Fatal(err) } } loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{}) if err != nil { t.Fatal(err) } calls := 0 transport := transportFunc(func(r *http.Request) (*http.Response, error) { calls++ var body map[string]any if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Fatal(err) } if body["model"] != "fixture-model" || body["response_format"] == nil { t.Errorf("unexpected request: %v", body) } return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"model":"fixture-model","choices":[{"message":{"role":"assistant","content":"{\"status\":\"ok\"}"}}]}`)), Request: r}, nil }) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport}) if err != nil { t.Fatal(err) } results, err := VerifyStructuredOutput(context.Background(), runtime.Engine, []string{"fixture"}, nil) if err != nil || calls != 1 || len(results) != 1 || results[0].Status != VerificationSuccess { t.Fatalf("calls=%d results=%+v err=%v", calls, results, err) } } func TestVerificationIdentifiesProfileBeforeDispatch(t *testing.T) { var current string engine := smokeFunc(func(_ context.Context, req pk.SmokeTestRequest) (*pk.SmokeTestReport, error) { if current != req.ProfileID { t.Fatalf("progress %q before dispatch %q", current, req.ProfileID) } return positiveSmokeReport(), nil }) _, err := VerifyStructuredOutput(context.Background(), engine, []string{"one", "two"}, func(id string) { current = id }) if err != nil { t.Fatal(err) } }