droboticflow-new/internal/api/initial_slice_confirmation_matrix_test.go
Codex d43f622ec8 🛡️ Close annotation recovery and save reconciliation gaps
Preserve legacy system suggestions and unreadable saved content across workspace writers. Compare explicit dictionary snapshots and normalize empty optional evidence during save readback; keep transient autosave failures retryable. Cover recovery entry points, source shapes, failed saves and stale-snapshot rejection with isolated HTTP and browser regressions.
2026-11-10 19:33:36 -08:00

174 lines
8.7 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"reflect"
"testing"
"time"
"droboticflow/internal/domain"
)
// System suggestion revision zero is not a previous human submission. Exercise
// the actual HTTP command and durable processor rather than just its flag.
func TestInitialSliceConfirmationSystemSuggestionMatrix(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
for _, history := range []string{"none", "slice-zero", "annotation-zero", "both-zero"} {
t.Run(history, func(t *testing.T) {
f, root := annotationProcessorFixture(t)
h := f.item
slices := []domain.SliceSegment{{ID: "s", Name: "测试切片", Start: 0, End: 4}}
actions := []domain.AnnotationSegment{{ID: "retained", Start: 0, End: 4, Status: "pending"}}
h.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions, "statuses": map[string]string{"s": "pending"}, "userId": f.annotator.ID, "savedAt": nowISO()}
h.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "editing", "phase": "slice"}
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
if history == "slice-zero" || history == "both-zero" {
if err := f.store.UpsertSliceRevision(f.ctx, domain.SliceRevisionRecord{ID: "suggested-slices", OrganizationID: h.OrganizationID, TaskID: f.task.ID, Revision: 0, AuthorUserID: "system", Segments: slices}); err != nil {
t.Fatal(err)
}
}
if history == "annotation-zero" || history == "both-zero" {
if err := f.store.UpsertAnnotationRevision(f.ctx, domain.AnnotationRevisionRecord{ID: "suggested-actions", OrganizationID: h.OrganizationID, TaskID: f.task.ID, Revision: 0, AuthorUserID: "system", Segments: actions}); err != nil {
t.Fatal(err)
}
}
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "sliceSegments": slices})
if r.Code != 202 {
t.Fatalf("system suggestions blocked first confirmation: %d %s", r.Code, r.Body)
}
now := time.Now().UTC()
job, err := f.store.ClaimAnnotationProcessing(f.ctx, "matrix-worker", now.Format(time.RFC3339Nano), now.Add(time.Minute).Format(time.RFC3339Nano))
if err != nil || job == nil {
t.Fatal("not durably accepted", err)
}
s := &server{store: f.store, workspaceMountPath: root, externalAnnotationProcessor: true}
s.executeAnnotationJob(context.Background(), *job)
after, _ := f.store.GetHumanItem(f.ctx, h.ID)
if after.ProcessingJob.Status != "completed" || !reflect.DeepEqual(decodeMaterializationValue[domain.AnnotationSegment](annotationWorkspacePayload(after)["segments"]), actions) {
t.Fatalf("saved actions not preserved: %+v", after.ProcessingJob)
}
oldSlices, _ := f.store.ListSliceRevisions(f.ctx, h.OrganizationID, f.task.ID)
oldActions, _ := f.store.ListAnnotationRevisions(f.ctx, h.OrganizationID, f.task.ID)
if (history == "slice-zero" || history == "both-zero") && !slicesContainSuggestion(oldSlices) {
t.Fatal("generation removed the original suggestion")
}
if (history == "annotation-zero" || history == "both-zero") && (len(oldActions) != 1 || oldActions[0].ID != "suggested-actions") {
t.Fatal("generation removed suggested actions")
}
})
}
}
// Cover canonical saves and explicit disposition operations before first
// generation. All mutation routes below operate only on this isolated fixture.
func TestInitialSliceConfirmationSavedShapeMatrix(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
for _, shape := range []string{"saved-keep", "saved-split", "all-discard", "restore-discard"} {
t.Run(shape, func(t *testing.T) {
f, root := annotationProcessorFixture(t)
reason := dispositionFixturePayload(t, f)
h := f.item
slices := []domain.SliceSegment{{ID: "s", Name: "测试切片", Start: 0, End: 4}}
actions := []domain.AnnotationSegment{{ID: "saved-description", Start: 0, End: 4, Description: "保留人工描述", Status: "described"}}
h.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions, "statuses": map[string]string{"s": "labeled"}, "userId": f.annotator.ID, "savedAt": nowISO()}
h.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "editing", "phase": "slice"}
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
if shape == "saved-split" {
slices = []domain.SliceSegment{{ID: "left", Name: "测试切片", Start: 0, End: 2, SourceIDs: []string{"s"}}, {ID: "right", Name: "测试切片", Start: 2, End: 4, SourceIDs: []string{"s"}}}
actions = []domain.AnnotationSegment{{ID: "left-action", Start: 0, End: 2, Description: "左侧描述", Status: "described"}, {ID: "right-action", Start: 2, End: 4, Status: "invalid"}}
}
if shape == "all-discard" || shape == "restore-discard" {
body := reason
body.Version = h.Version
body.SliceSegments = slices
body.Segments = actions
body.SliceID = "s"
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("discard: %d %s", r.Code, r.Body)
}
hptr, _ := f.store.GetHumanItem(f.ctx, h.ID)
h = *hptr
if shape == "restore-discard" {
var restored combinedAnnotationDraftInput
raw, _ := json.Marshal(annotationWorkspacePayload(&h))
if err := json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
body.combinedAnnotationDraftInput = restored
body.Version = h.Version
body.Disposition = "keep"
body.ResetToPending = true
body.Reason = ""
r = f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("restore: %d %s", r.Code, r.Body)
}
hptr, _ = f.store.GetHumanItem(f.ctx, h.ID)
h = *hptr
slices = decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(&h)["sliceSegments"])
slices[0].Name = "测试切片"
actions = decodeMaterializationValue[domain.AnnotationSegment](annotationWorkspacePayload(&h)["segments"])
} else {
slices = decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(&h)["sliceSegments"])
actions = decodeMaterializationValue[domain.AnnotationSegment](annotationWorkspacePayload(&h)["segments"])
}
}
saved := f.request(http.MethodPut, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/drafts", f.annotator, map[string]any{"version": h.Version, "sliceSegments": slices, "segments": actions})
if saved.Code != 200 {
t.Fatalf("save %s: %d %s", shape, saved.Code, saved.Body)
}
before, _ := f.store.GetHumanItem(f.ctx, h.ID)
selected, _, err := retainedSliceRecoveryInput(before, before.Version)
if err != nil {
t.Fatal(err)
}
expectedActions := decodeMaterializationValue[domain.AnnotationSegment](selected.RetryWorkspace["segments"])
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": before.Version, "sliceSegments": slices})
if r.Code != 202 {
t.Fatalf("saved %s rejected by confirmation: %d %s", shape, r.Code, r.Body)
}
now := time.Now().UTC()
job, err := f.store.ClaimAnnotationProcessing(f.ctx, "shape-worker", now.Format(time.RFC3339Nano), now.Add(time.Minute).Format(time.RFC3339Nano))
if err != nil || job == nil {
t.Fatal("not durably accepted", err)
}
processor := &server{store: f.store, workspaceMountPath: root, externalAnnotationProcessor: true}
processor.executeAnnotationJob(context.Background(), *job)
after, _ := f.store.GetHumanItem(f.ctx, h.ID)
if after.ProcessingJob.Status != "completed" {
t.Fatalf("generation failed: %+v", after.ProcessingJob)
}
workspace := annotationWorkspacePayload(after)
if got := decodeMaterializationValue[domain.AnnotationSegment](workspace["segments"]); !reflect.DeepEqual(got, expectedActions) {
t.Fatalf("%s lost actions: got %+v, want %+v", shape, got, expectedActions)
}
gotSlices := decodeMaterializationValue[domain.SliceSegment](workspace["sliceSegments"])
if len(gotSlices) != len(slices) {
t.Fatal("generation changed the saved slice count")
}
for i, slice := range gotSlices {
if slice.Start != slices[i].Start || slice.End != slices[i].End || slice.IsDiscarded() != slices[i].IsDiscarded() || !reflect.DeepEqual(slice.DiscardedAnnotations, slices[i].DiscardedAnnotations) {
t.Fatalf("%s changed saved structure or discarded evidence", shape)
}
}
})
}
}
func slicesContainSuggestion(revisions []domain.SliceRevisionRecord) bool {
for _, revision := range revisions {
if revision.ID == "suggested-slices" {
return true
}
}
return false
}